package com.xiaoyang.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoyang.service.RequestService;
import com.xiaoyang.service.WxPushService;
import com.xiaoyang.util.LocalCache;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author xiaoyang
 * @create 2020/7/8 8:37 下午
 */
@Service
public class RequestServiceImpl implements RequestService {

    public static OkHttpClient client = new OkHttpClient();

    @Value("${SESSION_URL}")
    private String SESSION_URL;

    @Value("${IMAGE_URL}")
    private String IMAGE_URL;

    @Value("${ACTIVE_URL}")
    private String ACTIVE_URL;

    @Value("${MEMORYIMAGE_URL}")
    private String MEMORYIMAGE_URL;

    @Autowired
    private WxPushService wxPushService;

    /**
     * 罗静老师ID
     */
    private String TEACHER_LUO_ID = "131669";

    private String TEACHER_GUO_ID = "131273";

    /**
     * 存放cookie
     */
    private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();

    private boolean hasResponseCookie = false;

    @Override
    public String getSession() {
        String session = LocalCache.get("session");
        return session;
    }

    /**
     * 获取请求
     *
     * @return
     */
    @Override
    public String saveSession(String session) {
        LocalCache.put("session", session);
        return session;
    }

    @Override
    public List<String> getAllImageList() {

        List<String> imageList = new ArrayList<>();
        try {
            String session = LocalCache.get("session");
            if (session == null) {
                return imageList;
            }
            Request request = new Request.Builder()
                    .url(IMAGE_URL)
                    .addHeader("session", session)
                    .addHeader("User-Agent", "Android/ONEPLUS A5010,4.5.6")
                    .build();
            Response response = client.newCall(request).execute();
            String json = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(json);
            JSONArray actions = jsonObject.getJSONObject("data").getJSONArray("actions");
            for (Object action : actions) {
                JSONObject act = (JSONObject) action;
                JSONArray images = act.getJSONArray("images");
                for (Object image : images) {
                    JSONObject img = (JSONObject) image;
                    String bigImageUrl = img.getString("bigImageUrl").replace("http", "https");
                    imageList.add(bigImageUrl);
                }
                JSONArray videos = act.getJSONArray("videos");
                for (Object video : videos) {
                    JSONObject vid = (JSONObject) video;
                    String videoUrl = vid.getString("videoUrl").replace("http", "https");
                    imageList.add(videoUrl);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            wxPushService.wxPush("session失效，快去重新抓取", "UID_iAB4BFMt7quFBtA4eFOeQl117fbZ");
        }

        return imageList;
    }

    @Override
    public List<String> getMemoryImageList() {
        List<String> memoryImageList = new ArrayList<>();
        try {
            String session = LocalCache.get("session");
            if (session == null) {
                return memoryImageList;
            }

            client = new OkHttpClient.Builder()
                    .cookieJar(new CookieJar() {
                        @Override
                        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                            cookieStore.put(url, cookies);
                            cookieStore.put(HttpUrl.parse(MEMORYIMAGE_URL), cookies);
                        }

                        @Override
                        public List<Cookie> loadForRequest(HttpUrl url) {
                            List<Cookie> cookies = cookieStore.get(HttpUrl.parse(MEMORYIMAGE_URL));
                            if (cookies != null) {
                                hasResponseCookie = true;
                            }
                            return cookies != null ? cookies : new ArrayList<Cookie>();
                        }
                    })
                    .build();

            Request request = new Request.Builder()
                    .url(MEMORYIMAGE_URL)
                    .addHeader("Session", session)
                    .build();
            Response response = client.newCall(request).execute();
            String json = response.body().string();

            if (hasResponseCookie) {
                // 处理数据
                JSONObject jsonObject = JSONObject.parseObject(json);
                JSONArray dataJsonArray = jsonObject.getJSONArray("data").getJSONObject(0).getJSONArray("traillist");
                for (Object dataJson : dataJsonArray) {
                    JSONObject data = (JSONObject) dataJson;
                    JSONArray imageListJson = data.getJSONArray("images");
                    for (Object image : imageListJson) {
                        JSONObject imageJson = (JSONObject) image;
                        String imageUrl = imageJson.getString("bigurl").replace("http", "https");
                        memoryImageList.add(imageUrl);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            wxPushService.wxPush("session失效，快去重新抓取", "UID_iAB4BFMt7quFBtA4eFOeQl117fbZ");
        }
        return memoryImageList;
    }

    @Override
    public Boolean activeSession() {
        try {
            String session = LocalCache.get("session");
            Request request = new Request.Builder()
                    .url(ACTIVE_URL)
                    .addHeader("session", session)
                    .addHeader("User-Identity", "e7655e29-e923-41ea-95bf-fb8df3244c36")
                    .build();
            Response response = client.newCall(request).execute();
            String json = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(json);
            if ("0".equals(jsonObject.getString("result"))) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
